const loadAllItems = require('../src/items')
const loadPromotions = require('../src/promotions')

function sameElements(inputs) {
    let result = [];
    let obj = {};
    for(let item of inputs){
      let ch = item.slice(0,8);
      let count = item.slice(11);
      if(!obj[ch]){
         obj[ch]={};
          obj[ch].id = ch;
          obj[ch].count = count;
      }else{
        obj[ch].count += count;
      }
    }
    for(let item in obj){
      result.push(obj[item]);
    }
    return result;
}
//数组整合
function input(){
  let allItems = loadAllItems();
   let arr_inputs = sameElements(inputs);
    for(let item1 of allItems){
      for(let item2 of arr_inputs){
        if(item1.id===item2.id){
          item2.name = item1.name;
          item2.price = item1.price;
          item2.allPrice = item1.price*item2.count;
        }
      }
    }
    return arr_inputs;
}//完全整合

function print(){
  let summary = 0;
  let sum1,sum1_1,sum2_2;
  let sum2=0;
  let sum = '';
   let arr = [];
   let menu = '';
   let pro = '';
   let all='';
   let arr_input = input(input);
   let promotions = loadPromotions()[1].items;
   for(let item of arr_input){
      menu +=`${item.name} x ${item.count} = ${item.allPrice}元\n`
      summary += item.allPrice;
          if(summary >= 30){
            sum1 = summary-parseInt(summary/30)*6;
            sum1_1 = summary-sum1;
          }
        }
     
      for(let item of arr_input){
          if(promotions.indexOf(item.id)!=-1){
              item.allPrice=item.allPrice/2;
          }else{
            item.allPrice = item.allPrice;
          }
          sum2 += item.allPrice;
          sum2_2 = summary - sum2;
      }
      if(sum1<=sum2){
        pro +=`满30减6元，省${sum1_1}元\n`;
        sum +=`${sum1}`;
      }else{
        pro +=`指定菜品半价(黄焖鸡，凉皮)，省${sum2_2}元\n`
        sum+=`${sum2}`;
      }
   arr.push(menu);
   arr.push(pro);
   arr.push(sum);
   return arr;
}

function bestCharge(inputs) {
  //  let arr_input1 = sameElements(inputs);
  //  let arr_inputs = input(arr_input1);
  //  console.log(arr_inputs);
   let arr = print();
   let str = '============= 订餐明细 =============\n'+
    arr[0]+
   '-----------------------------------\n'+
   '使用优惠:\n'+ arr[1]+
   '-----------------------------------\n'+
  `总计：${arr[2]}元\n`+
   '===================================';
   console.log(str);
   return str;
}
// let inputs = ["ITEM0001 x 1", "ITEM0013 x 2", "ITEM0022 x 1"];
// let inputs = ["ITEM0013 x 4"];
// let inputs = ["ITEM0013 x 4", "ITEM0022 x 1"];
//  let cct = bestCharge(inputs);
module.exports = bestCharge;